package com.jacob.androidframe.controls;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.widget.Button;

public class TimerButton extends Button {
	/** 倒计时的总时长，这里是60秒 */
	private static final long MILLIS_IN_FUTURE = 60000;
	/** 倒计时的时间间隔，这里是1秒 */
	private static final long COUNTDOWN_INTERVAL = 1000;
	/** 倒计时开始后显示的文字 */
	private static final String COUNTDOWN_TEXT = "%1$d秒后可重新点击";
	/** 保存倒计时前显示的文字 */
	private CharSequence mText;
	
	private TimeCountTask mTimeCountTask;

	public TimerButton(Context context)
	{
		super(context);
		mTimeCountTask = new TimeCountTask(MILLIS_IN_FUTURE, COUNTDOWN_INTERVAL);
		mText = this.getText();
	}

    public TimerButton(Context context, AttributeSet attrs) {
    	super(context, attrs);
    	mTimeCountTask = new TimeCountTask(MILLIS_IN_FUTURE, COUNTDOWN_INTERVAL);
    	mText = this.getText();
    }

    public TimerButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mTimeCountTask = new TimeCountTask(MILLIS_IN_FUTURE, COUNTDOWN_INTERVAL);
        mText = this.getText();
    }
    
    public void startCountDown()
	{
    	mTimeCountTask.start();
	}
	
    private class TimeCountTask extends CountDownTimer
    {

		public TimeCountTask(long millisInFuture, long countDownInterval)
		{
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onTick(long millisUntilFinished)
		{
			TimerButton.this.setEnabled(false);
			TimerButton.this.setText(String.format(COUNTDOWN_TEXT, millisUntilFinished /1000));
		}

		@Override
		public void onFinish()
		{
			TimerButton.this.setEnabled(true);
			TimerButton.this.setText(mText);
		}
    	
    }
}
